package com.teacher;

/**
 * 模拟银行取款业务，展示并发安全问题
 */
public class Bank {
    private int account = 20000;//账号余额

    public boolean getMoney(int money){
        //1查询账号余额
        int account = getAccount();
        //2判断余额是否足够
        if(account >= money){
            //3.如果足够，则取款,计算新余额
            account = account - money;
            //yield方法的作用是让当前线程放弃本次剩余时间片
            Thread.yield();//模拟时间片耗尽
            //4.更新余额
            saveAccount(account);
            //允许出钞
            return true;
        }
        return false;//余额不足，拒绝出钞
    }

    public void saveAccount(int account){
        this.account = account;
    }

    public int getAccount(){
        return account;
    }
}







